//
//  RwdStatusListModel.swift
//  Weibo_rwd
//
//  Created by 任文迪 on 16/7/14.
//  Copyright © 2016年 spaceX. All rights reserved.
//

import UIKit

class RwdStatusListModel: NSObject {
    
    //微博数据是rwdStatusModel类型的数组懒加载 一下
    lazy var Status: [RwdStatusViewModel] = [RwdStatusViewModel]()
    
    
    
    func loadSomething(isPullUp:Bool,callBack:(isSuccess: Bool)->()) {
        
        var maxId:Int64 = 0
        var sinceId:Int64 = 0
        
        if isPullUp{
            maxId = Status.last?.status?.id ?? 0
            if maxId > 0 {
                
                maxId -= 1
            }
        }else {
            
            sinceId = Status.first?.status?.id ?? 0
        }
        
        
        RwdNetworkTools.sharedTools.loadStatus(maxId, sinceId: sinceId){ (response, error) -> () in
            
            //如果有错误信息就返回
            if error != nil {
                callBack(isSuccess: false)
                print(error)
                return
                
            }
            //代码到此肯定有数据
            guard let dict = response as? [String:AnyObject] else {
                //格式不对就返回
                callBack(isSuccess: false)
                return
                
            }
            guard let statusArr = dict["statuses"] as? [[String:AnyObject]] else {
                //格式有误
                callBack(isSuccess: false)
                return
                
            }
            //设定一个零时数组类型为RwdStatusModel
            var tempArray = [RwdStatusViewModel]()
            
            for statusDict in statusArr {
                //赋值给cell
                let status = RwdStatusModel(dict: statusDict)
                //赋值给viewmodel
                let statusModel = RwdStatusViewModel(status: status)
                
                tempArray.append(statusModel)
                
            }
            
            
            if isPullUp {
                self.Status.appendContentsOf(tempArray)
                
            }else {
                
                self.Status.insertContentsOf(tempArray, at: 0)
                
            }
            
            callBack(isSuccess: true)
            
            
            
            
            
        }
    }
    
}
